import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
import { catchError, map } from 'rxjs/operators';
import { NzMessageService } from 'ng-zorro-antd';

import { SUCCESS, LOGIN } from '../config';

@Injectable()

export class RequestService {
  ROOT_URL: string = ROOT_URL;
  private headerOpt: object = {
    headers: new HttpHeaders({
      token: localStorage.token
    })
  };

  constructor(
    private http: HttpClient,
    private msg: NzMessageService
  ) {}
  
  get(url: string, params: object = {}) {
    return new Promise((resolve, reject) => {
      const options = Object.assign({}, this.headerOpt)
      options['params'] = params
      this._request(url, options).subscribe(data => {
        if (data) {
          resolve(data)
        }
      })
    })
  }

  post(url: string, params: object = {}) {
    return new Promise((resolve, reject) => {
      this._request(url, params, this.headerOpt, 'post').subscribe(data => {
        if (data) {
          resolve(data)
        }
      })
    })
  }

  _request(url: string, params: object = {}, header: object = {}, method: string = 'get'): Observable <any[]> {
    return this.http[method](ROOT_URL + url, params, header)
      .pipe(
        map(this.extractData),
        catchError(this.handleError) // 处理服务器报错
      );
  }

  private extractData(res: any) {
    if (res.code === SUCCESS) {
      return res;
    } else if (res.code === LOGIN) {
      location.reload();
    } else {
      alert(res.msg)
      // this.msg.error(res.msg)
    }
    return false
  }

  private handleError (error: Response | any) {
    console.log(error)
    return error
  }

}